package com.aiserver.service.impl;

import com.aiserver.service.SmsService;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20210111.models.SendStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 腾讯云短信服务实现
 */
@Service
public class TencentSmsServiceImpl implements SmsService {

    private static final Logger logger = LoggerFactory.getLogger(TencentSmsServiceImpl.class);

    @Value("${sms.tencent.secret-id:}")
    private String secretId;

    @Value("${sms.tencent.secret-key:}")
    private String secretKey;

    @Value("${sms.tencent.app-id:}")
    private String appId;

    @Value("${sms.tencent.sign-name:}")
    private String signName;

    @Value("${sms.tencent.template-id:}")
    private String templateId;

    @Value("${sms.tencent.region:ap-beijing}")
    private String region;

    @Override
    public boolean sendCode(String phone, String code) {
        return sendSms(phone, templateId, new String[]{code});
    }

    @Override
    public boolean sendSms(String phone, String templateId, String[] params) {
        try {
            // 检查配置
            if (isEmpty(secretId) || isEmpty(secretKey) || isEmpty(appId) || isEmpty(signName)) {
                logger.warn("腾讯云短信配置不完整，跳过发送短信到: {}", phone);
                logger.info("模拟发送短信验证码到 {}: {}", phone, params.length > 0 ? params[0] : "");
                return true; // 开发环境返回成功
            }

            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey
            Credential cred = new Credential(secretId, secretKey);

            // 实例化一个http选项，可选，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setReqMethod("POST");
            httpProfile.setConnTimeout(60);
            httpProfile.setEndpoint("sms.tencentcloudapi.com");

            // 实例化一个client选项，可选，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setSignMethod("HmacSHA256");
            clientProfile.setHttpProfile(httpProfile);

            // 实例化要请求产品的client对象
            SmsClient client = new SmsClient(cred, region, clientProfile);

            // 实例化一个请求对象
            SendSmsRequest req = new SendSmsRequest();

            // 短信应用ID
            req.setSmsSdkAppId(appId);

            // 短信签名内容
            req.setSignName(signName);

            // 模板ID
            req.setTemplateId(templateId);

            // 下发手机号码，采用E.164标准，+[国家或地区码][手机号]
            String[] phoneNumbers = {"+86" + phone};
            req.setPhoneNumberSet(phoneNumbers);

            // 模板参数
            req.setTemplateParamSet(params);

            // 返回的resp是一个SendSmsResponse的实例，与请求对象对应
            SendSmsResponse resp = client.SendSms(req);

            // 检查发送结果
            SendStatus[] sendStatusSet = resp.getSendStatusSet();
            if (sendStatusSet != null && sendStatusSet.length > 0) {
                SendStatus status = sendStatusSet[0];
                if ("Ok".equals(status.getCode())) {
                    logger.info("短信发送成功到 {}, SerialNo: {}", phone, status.getSerialNo());
                    return true;
                } else {
                    logger.error("短信发送失败到 {}, Code: {}, Message: {}", phone, status.getCode(), status.getMessage());
                    return false;
                }
            } else {
                logger.error("短信发送失败到 {}, 未收到响应状态", phone);
                return false;
            }

        } catch (TencentCloudSDKException e) {
            logger.error("腾讯云短信发送异常到 {}: {}", phone, e.getMessage(), e);
            return false;
        } catch (Exception e) {
            logger.error("短信发送异常到 {}: {}", phone, e.getMessage(), e);
            return false;
        }
    }

    /**
     * 检查字符串是否为空
     */
    private boolean isEmpty(String str) {
        return str == null || str.trim().isEmpty();
    }
}